package com.xm.runtimetask.util;


import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import com.xm.runtimetask.AutoSwipService;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.List;

import javax.security.auth.login.LoginException;

/**
 * Created by Administrator on 2017/7/13.
 *
 */

public class TimeTaskUtil {

    public static final String TIMETASK_START_EVERYDAY_ACTION = "com.xm.runtimetask.task.start.everyday.action";
    public static final String TIMETASK_STOP_EVERYDAY_ACTION = "com.xm.runtimetask.task.stop.everyday.action";
    public static final String TIMETASK_STOP_ACTION = "com.xm.runtimetask.task.stop.action";
    public static final String TIMETASK_RUN_ACTION = "com.xm.runtimetask.task.run.action";
    public static final String TIMETASK_RUN_STOP_ACTION = "com.xm.runtimetask.task.run.stop.action";
    public static final String TIMETASK_UNRUN_CHECK_LOCK_SCREEN_ACTION = "com.xm.runtimetask.task.unrun.checklockscreen.action";
    public static final String startTaskEveryDayTime =  "7:15";
    private volatile static  TimeTaskUtil timeTaskUtil;
    private Application application;

    private TimeTaskUtil(){

    }

    public static TimeTaskUtil getInstance(Application application){
        if (timeTaskUtil == null){
            synchronized (TimeTaskUtil.class){
                if (timeTaskUtil == null){
                    timeTaskUtil = new TimeTaskUtil();
                }
            }
        }
        timeTaskUtil.application = application;
        return timeTaskUtil;
    }

    //=============================每天自动启动闹钟==================start=============//
    /** 启动每天开始定时任务定时器 */
    public void startTimeTaskEveryDayAlarm() {
        cancelTimeTaskEveryDayAlarm();
        String []hourMinuteArray = startTaskEveryDayTime.split(":");
        Calendar now = Calendar.getInstance();
        Calendar targetTime = (Calendar) now.clone();
        targetTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinuteArray[0]));
        targetTime.set(Calendar.MINUTE, Integer.parseInt(hourMinuteArray[1]));
        targetTime.set(Calendar.SECOND, 0);
        targetTime.set(Calendar.MILLISECOND, 0);
        if (targetTime.before(now)){
            targetTime.add(Calendar.DATE, 1);
        }
        setRepeatAlarm(AlarmManager.RTC_WAKEUP,targetTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                11, TIMETASK_START_EVERYDAY_ACTION);
        setIsStartEveryDayTask(true);
    }

    private void setRepeatAlarm(int type, long triggerAtMillis, Long intervalMillis, int requestCode, String action) {
        // 方便测试，这里指定即时启动，每20秒执行一次
        //setAlarm(type, 0, 20 * 1000, requestCode, action)
        Intent intent = new Intent();
        intent.setClass(application, AutoSwipService.class);
        intent.setAction(action);
        PendingIntent pi = PendingIntent.getService(application, requestCode, intent, 0);
        AlarmManager alarmManager = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(type, triggerAtMillis, intervalMillis,pi);
        //alarmManager.setRepeating(type, 10 * 1000, 20 * 1000,pi);
    }

    /** * 取消每天开始定时任务定时器*/
    public void cancelTimeTaskEveryDayAlarm() {
        AlarmManager alarmManager = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(
                PendingIntent.getBroadcast(application,
                        11,new Intent(TIMETASK_STOP_EVERYDAY_ACTION)
                        , PendingIntent.FLAG_UPDATE_CURRENT));
        setIsStartEveryDayTask(false);
    }
    //===========================每天自动启动闹钟==============end===============//

    //===========================运行定时任务==============start===============//
    /**
     * 开始定时任务
     * @param runTotalSecodes
     */
    public void startTimeTask(int runTotalSecodes)
    {
        stopRunTimeTask();
        final long UPLOADGPS_TASK_INTERVAL = 1000 * runTotalSecodes;//时间间隔
        Intent i = new Intent();
        i.setClass(application, AutoSwipService.class);
        i.setAction(TIMETASK_STOP_ACTION);
        PendingIntent pi = PendingIntent.getService(application, 33, i, 0);
        AlarmManager alarmMgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + UPLOADGPS_TASK_INTERVAL, pi);
        setIsTimeTaskRuning(true);
        //启动任务
        Intent intent = new Intent(application,AutoSwipService.class);
        intent.setAction(TIMETASK_RUN_ACTION);
        application.startService(intent);

    }

    /**
     * 执行定时任务循环
     */
    public void runTimeTask(int secodes)
    {
        if (!isTimeTaskRuning()){//已经停止了
            return;
        }
        final long UPLOADGPS_TASK_INTERVAL = 1000 * secodes;//时间间隔
        Intent i = new Intent();
        i.setClass(application, AutoSwipService.class);
        i.setAction(TIMETASK_RUN_ACTION);
        PendingIntent pi = PendingIntent.getService(application, 66, i, 0);
        AlarmManager alarmMgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //参数2是开始时间、参数3是允许系统延迟的时间
            alarmMgr.setWindow(AlarmManager.RTC,
                    System.currentTimeMillis() + UPLOADGPS_TASK_INTERVAL, UPLOADGPS_TASK_INTERVAL, pi);
        } else {
            alarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + UPLOADGPS_TASK_INTERVAL, pi);
        }
    }
    /**
     * 停止定时任务循环
     */
    public void stopRunTimeTask()
    {
        setIsTimeTaskRuning(false);
        Intent i = new Intent();
        i.setClass(application, AutoSwipService.class);
        i.setAction(TIMETASK_RUN_STOP_ACTION);
        PendingIntent pi = PendingIntent.getService(application, 66, i, 0);
        AlarmManager alarmMgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.cancel(pi);
    }

    private void  setIsTimeTaskRuning(boolean isTimeTaskRuning){
        Remember.putBoolean("isTimeTaskRuning",isTimeTaskRuning);
    }
    public boolean isTimeTaskRuning(){
        return Remember.getBoolean("isTimeTaskRuning",false);
    }
    //===========================运行定时任务==============end===============//

    private void  setIsStartEveryDayTask(boolean isStartEveryDayTask){
        Remember.putBoolean("isStartEveryDayTask",isStartEveryDayTask);
    }
    public boolean isStartEveryDayTask(){
        return Remember.getBoolean("isStartEveryDayTask",false);
    }


    //=======================定时任务结束后空闲期间检查屏幕是否锁屏关闭=======start=============//
    /** 启动每天开始定时任务定时器 */
    public void startCheckLockScreenAlarm() {
        cancelCheckLockScreenAlarm();
        long triggerAtMillis = System.currentTimeMillis() + 1000*60*60*1;
        setRepeatAlarm(AlarmManager.RTC_WAKEUP, triggerAtMillis, AlarmManager.INTERVAL_HOUR,
                77, TIMETASK_UNRUN_CHECK_LOCK_SCREEN_ACTION);
        setIsStartEveryDayTask(true);
    }

    /** * 取消每天开始定时任务定时器*/
    public void cancelCheckLockScreenAlarm() {
        AlarmManager alarmManager = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(
                PendingIntent.getBroadcast(application,
                        77,new Intent(TIMETASK_UNRUN_CHECK_LOCK_SCREEN_ACTION)
                        , PendingIntent.FLAG_UPDATE_CURRENT));
        setIsStartEveryDayTask(false);
    }
    //=======================定时任务结束后空闲期间检查屏幕是否锁屏关闭========end============//

}

